<template>

    <div class="team-management-page">
        <!-- 团队信息区域 -->
        <div class="flex">
            <div class="blue-radius"></div>
            <h2 class="page-title">新增团队信息</h2>
        </div>

        <el-form :model="teamInfo" label-width="100px" class="team-info-form">
            <div class="section-header">团队信息</div>
            <el-row :gutter="24">
                <!-- 团队编号 -->
                <el-col :span="8">
                    <el-form-item label="团队编号">
                        <el-input v-model="teamInfo._id" disabled />
                    </el-form-item>
                </el-col>

                <!-- 团队名称 -->
                <el-col :span="8">
                    <el-form-item label="团队名称">
                        <el-input v-model="teamInfo.name" placeholder="请输入团队名称" />
                    </el-form-item>
                </el-col>

                <!-- 团队头像上传 -->
                <el-col :span="8">
                    <el-form-item label="团队头像">
                        <el-upload class="avatar-uploader" action="http://nocat.life:3012/images/upload"
                            :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img class="avatar-img" v-if="teamInfo.avatar" :src="teamInfo.avatar" />
                            <div v-if="!teamInfo.avatar"><el-avatar :icon="UserFilled" /></div>
                            <el-link class="uploadAvatar" type="primary">+点击上传</el-link>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>



            <el-row :gutter="24" class="second">
                <!-- 所属机构 -->
                <el-col :span="8">
                    <el-form-item label="所属机构">
                        <el-select v-model="teamInfo.organizationId" placeholder="请选择所属机构" clearable>
                            <el-option v-for="item in organizationsData.rows" :key="item._id" :label="item.name"
                                :value="item._id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <!-- 团队标签 -->
                <el-col :span="8">
                    <el-form-item label="团队标签">
                        <el-select v-model="teamInfo.tagIds" multiple placeholder="请选择团队标签">
                            <el-option v-for="item in tagOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>


        <!-- 团队成员区域 -->
        <div class="section-header">团队成员 ({{ teamManager.length }})</div>
        <div class="member-list">
            <el-card v-for="member in teamManager" :key="member._id" class="member-card">
                <div class="card-content">
                    <!-- 头像（动态绑定后端头像地址） -->
                    <div class="member-avatar" :style="{
                        backgroundImage: `url(${member.avatar})`,
                        backgroundSize: 'cover',
                        backgroundPosition: 'center'
                    }">
                    </div>

                    <!-- 成员信息 -->
                    <div class="member-details">
                        <div class="name-title">
                            <span class="member-name">{{ member.name }}</span>
                            <span class="member-title">{{ member.title }}</span>
                        </div>
                        <div class="signed-count">签约人数 {{ member.signedCount }}</div>
                        <div class="member-tags">
                            <!-- 团队长标签 -->
                            <el-tag v-if="member.isLeader" type="warning">团队长</el-tag>
                            <!-- 动态标签 -->
                            <el-tag v-for="tag in member.tags" :key="tag" :type="getTagType(tag)">{{ tag }}</el-tag>
                        </div>
                    </div>
                </div>

                <!-- 卡片底部按钮（跳转详情） -->
                <template #footer>
                    <el-button type="text" @click="viewDoctorDetail(member._id)">医师详情</el-button>
                </template>
            </el-card>
        </div>


        <!-- 服务包模块 -->
        <div class="service-card" style="margin-top: 20px;">
            <div class="card-header" style="margin-bottom: 20px;">服务包 ({{ servicePackages.length }})</div>
            <el-row>
                <el-col :span="8" v-for="pkg in servicePackages" :key="pkg._id">
                    <el-card style="margin-inline: 25px;margin-bottom: 20px;">
                        <div class="flex-around">
                            <!-- 头像（动态绑定后端头像地址） -->
                            <div class="member-avatar" :style="{
                                backgroundImage: `url(${pkg.image})`,
                                backgroundSize: 'cover',
                                backgroundPosition: 'center'
                            }">
                            </div>
                            <div>
                                <div class="pkg-header">
                                    <span>{{ pkg.name }}</span>
                                </div>
                                <div class="pkg-info">
                                    <p>服务对象：所有人</p>
                                </div>
                            </div>
                        </div>

                        <div class="pkg-action flex-between">
                            <div class="triangle-box" :class="{ active: pkg.state === 1, inactive: pkg.state === 0 }">
                            </div>
                            <div class="triangle-box-small"
                                :class="{ active: pkg.state === 1, inactive: pkg.state === 0 }">
                            </div>
                            <div class="service-state">{{ pkg.state === 1 ? '使用中' : '已停用' }}</div>
                            <el-button type="text" @click="viewPackageDetail(pkg._id)">服务包详情</el-button>
                        </div>
                    </el-card>
                </el-col>
                <!-- 添加服务包按钮 -->
                <el-col :span="7">
                    <el-card class="service-item add-pkg" @click="openServicePackModal">
                        <div class="add-icon">
                            <i class="el-icon-plus">+</i>
                            <p>添加服务包</p>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>


        <el-form-item class="button-box">
            <el-button type="primary" @click="addTeamData">保存</el-button>
            <el-button onclick="history.back()">返回</el-button>
        </el-form-item>
    </div>


    <TeamServicePackAdd :visible="isServicePackModalVisible" @close="closeServicePackModal"
        @confirm="handleServicePackConfirm" />
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { addTeamsApi, } from '../../api/teamManage'
import { useFindData } from '../../composables/findData'
import { detailDoctorsApi } from '../../api/doctors'
import { useRouter } from 'vue-router'
import TeamServicePackAdd from './TeamServicePackAdd.vue'
import { UserFilled } from '@element-plus/icons-vue'

const router = useRouter()


const { organizationsData, findOrganizationsDataAsync, } = useFindData()
// 团队信息初始值
const teamInfo = ref({
    name: '',
    leaderId: "686f2fdd0b991e21ee16fc06",
    organizationId: '',
    tagIds: '',
    avatar: '',
    servicePackIds: []
})
// 服务包
const servicePackages = ref([])

// 团队标签选项
const tagOptions = ref([
    { label: '高血压', value: '67c90bff35738d92907c1454' },
    { label: '低血糖', value: '67cfaeb34786f92b365536b5' },
    { label: '冠心病', value: '67cfaec04786f92b365536b7' },
    { label: '心律不齐', value: '686f67db5a2300006e007fb4' },
    { label: '高胆固醇', value: '67c90c0635738d92907c1458' },

])

// 团队队长数据
const teamManager = ref([
    {
        _id: "686f2fdd0b991e21ee16fc06",
        name: '李小明',
        title: '全科医师',
        signedCount: 100,
        tags: ['高血压', '老年护理'],
        avatar: 'https://woniumd.oss-cn-hangzhou.aliyuncs.com/web/jianglan/202507101045165.png  '
    }
])


// 头像上传前校验
const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isImage) {
        ElMessage.error('请上传图片文件！')
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB！')
    }
    return isImage && isLt2M
}

// 头像回显
const handleAvatarSuccess = (res) => {
    if (res.code == 200) {
        teamInfo.value.avatar = res.data;
    }
};

// 标签类型映射
const getTagType = (tag) => {
    switch (tag) {
        case '高血压':
            return 'danger'
        case '低血糖':
            return 'danger'
        case '冠心病':
            return 'danger'
        case '心律不齐':
            return 'danger'
        case '高胆固醇':
            return 'danger'
        case '老年护理':
            return 'success'
        default:
            return 'info'
    }
}

// 查看医师详情
const viewDoctorDetail = (doctor_id) => {
    router.push(`/data/doctor/detail/${doctor_id}`)
}

// 查看服务包详情
const viewPackageDetail = (pkg_id) => {
    router.push(`/data/servicePack/detail/${pkg_id}`)
}

// 显示所有机构，医生详情
onMounted(() => {
    findOrganizationsDataAsync()
    searchDoctorDetail()
})

// 添加请求
function addTeamData() {
    teamInfo.value.servicePackIds = servicePackages.value.map(pkg => pkg._id);
    addTeamsApi({
        ...teamInfo.value
    })
        .then(res => {
            if (res.code == 200) {
                console.log(teamInfo.value);
                ElMessage({
                    type: 'success',
                    message: '新增团队成功'
                })
                // 新增成功后，返回上一界面
                router.back();
            }
        })
}


// 控制子组件弹窗的显示状态
const isServicePackModalVisible = ref(false);

// 打开弹窗
const openServicePackModal = () => {
    isServicePackModalVisible.value = true;
};

// 关闭弹窗
const closeServicePackModal = () => {
    isServicePackModalVisible.value = false;
};


const handleServicePackConfirm = (selectedServicePacks) => {
    console.log(selectedServicePacks);
    // 遍历新选择的服务包，逐个添加（避免重复）
    selectedServicePacks.forEach(newPkg => {
        // 检查当前服务包是否已存在（通过_id判断）
        const isExists = servicePackages.value.some(existPkg => existPkg._id === newPkg._id);
        if (!isExists) {
            servicePackages.value.push(newPkg); // 追加到现有数组中
        }
    });
    closeServicePackModal(); // 关闭弹窗
};


// 获取一个医生详情
function searchDoctorDetail() {
    detailDoctorsApi({
        _id: '686f2fdd0b991e21ee16fc06'
    })
        .then(res => {
            if (res.code == 200) {
                console.log(res.data);
            }
        })
}


</script>

<style scoped>
.page-title {
    margin: 0 0 16px;
    font-size: 18px;
    font-weight: 550;
    color: #333333E5;
}

.blue-radius {
    border-width: 0px;
    width: 6px;
    height: 20px;
    background: inherit;
    background-color: rgba(41, 132, 248, 1);
    border: none;
    border-radius: 8px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    margin-top: 4px;
    margin-right: 10px;
}

.team-management-page {
    padding: 24px;
    background-color: #fff;
}

.section-header {
    font-size: 16px;
    font-weight: 500;
    margin: 16px 0;
    padding-left: 8px;
}

.team-info-form {
    background: #fff;
    border-top: 1px solid #f5f7fa;
    border-bottom: 1px solid #f5f7fa;
    padding-bottom: 24px;
}

.second {
    margin-top: -70px;
}

/* 头像上传样式 */
.avatar-uploader {
    width: 120px;
    height: 120px;
}

.avatar-img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
}

.uploadAvatar {
    margin-left: 10px;
}


/* 成员列表布局 */
.member-list {
    display: flex;
    flex-wrap: wrap;
    gap: 24px;
}

/* 成员卡片样式 */
.member-card {
    width: 340px;
    margin-left: 33px;
    transition: all 0.3s;
}

.member-card:hover {
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.card-content {
    display: flex;
    align-items: center;
    padding: 16px;
}

/* 头像色块 */
.member-avatar {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    margin-right: 16px;
}


/* 成员信息区域 */
.member-details {
    flex: 1;
}

.name-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 8px;
}

.member-name {
    font-size: 16px;
    margin-right: 8px;
}

.member-title {
    font-size: 12px;
    color: #666;
}

.signed-count {
    font-size: 12px;
    color: #999;
    margin-bottom: 8px;
}

.member-tags {
    font-size: 13px;
    display: flex;
    gap: 8px;
}

.button-box {
    border-top: 1px solid #f5f7fa;
    margin-top: 30px;
    padding-block: 20px;
}

.service-card {
    font-size: 16px;
    font-weight: 500;
    margin: 16px 0;
    padding-left: 8px;
}

.service-item {
    height: 70%;
}

.pkg-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 16px;
    font-weight: 500;
}

.pkg-info {
    margin-bottom: 16px;
    font-size: 12px;
    color: #999999;
}

.pkg-action {
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #f5f7fa;
}

/* 添加服务包卡片核心样式 */
/* 服务包卡片容器：确保子元素绝对定位相对于自身 */
.el-card {
    position: relative;
    overflow: hidden;
    /* 可选：防止角标超出卡片 */
}

/* 蓝色三角（角标背景） */
.triangle-box {
    position: absolute;
    top: 0;
    /* 顶部对齐 */
    right: 0;
    /* 右侧对齐 */
    width: 0;
    height: 0;
    /* 用边框实现三角（替代原来的clip-path，更简单） */
    border-top: 60px solid var(--el-color-primary);
    /* 蓝色，对应“使用中” */
    border-left: 60px solid transparent;
    clip-path: none;
    /* 移除原clip-path，避免冲突 */
    transform: none;
    /* 移除原旋转，边框已实现三角方向 */
}

/* 白色小三角（切角效果） */
.triangle-box-small {
    position: absolute;
    top: 0;
    right: 0;
    width: 0;
    height: 0;
    border-top: 20px solid white;
    border-left: 20px solid transparent;
    clip-path: none;
    transform: none;
}

/* 状态文本（定位在三角上） */
.service-state {
    position: absolute;
    top: 12px;
    right: 2px;
    font-size: 12px;
    font-weight: 500;
    color: #ffffff;
    transform: rotate(45deg);
}

/* 已停用状态 */
.triangle-box.inactive {
    border-top-color: #e55a5a;
}

.add-pkg {
    margin-left: 25px;
    cursor: pointer;
    text-align: center;
    padding: 20px 0;
    background-color: #f8fafc;
    /* 浅蓝背景，匹配设计图 */
    transition: background-color 0.3s ease;
    /* 平滑过渡 */
}

/* hover时背景加深 */
.add-pkg:hover {
    background-color: #e6f2fa;
    /* 颜色可根据设计微调，如#ecf5ff */
}

/* 图标和文字容器（垂直居中） */
.add-icon {
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* 加号图标样式 */
.add-icon i {
    font-size: 40px;
    color: #87cefa;
    /* 浅蓝色，匹配设计图的加号颜色 */
}

/* 文字样式 */
.add-icon p {
    margin-top: 8px;
    color: #87cefa;
    /* 与图标同色 */
    font-size: 14px;
    /* 调整字号，适配设计图视觉 */
}

/* 修改 placeholder 颜色 */
::v-deep .el-input__inner::placeholder {
    color: #ccc;
    /* 浅灰色，可按需调整 */
}
</style>